#include "Dict.h"
#include <stdlib.h>
#include <stdio.h>
#include <assert.h>

struct sDict
{
	Hash hash;
	int tam;
};

Dict
dict_empty (void)
{
	Dict retorno =NULL;
	retorno=(Dict)calloc(1,sizeof(struct sDict));
	if(retorno == NULL)
		return NULL;
	retorno -> hash = hash_empty();
	retorno -> tam = 0;
	return retorno;
}


void
dict_add (Dict d, Word w, Def f)
{
	Key aux1=NULL;
	Data aux2=NULL;	
	assert(d != NULL);
	aux1=key_fromString(w);
	if(hash_exists(d -> hash,aux1) != TRUE)
	{
		aux2=data_fromString(f);
		hash_add(d -> hash,aux1,aux2);
		d -> tam = d -> tam + 1;
		data_destroy(aux2);
	}
	key_destroy(aux1);
}

Bool
dict_exists (Dict d, Word w)
{
	Key aux1 = NULL;
	Bool aux2 = FALSE;
	if(d == NULL)
		return FALSE;
	aux1=key_fromString(w);
	aux2=hash_exists(d -> hash,aux1);
	key_destroy(aux1);
	return aux2;
}

Def
dict_search (Dict d, Word w)
{
	Key k;
	Data da; 
	char *ptr;
	k = key_fromString(w);
	if(hash_exists( d->hash ,k) == TRUE)
	{
		da=hash_search(d -> hash,k);
		ptr=data_toString(da);
		data_destroy(da);
		key_destroy(k);
		return ptr;
	}
	else
	{
		return NULL;
	}
}

void
dict_del (Dict d, Key k)
{
	assert(d != NULL);
	if(hash_exists(d -> hash,k) == TRUE)
	{
		hash_del(d -> hash, k);
		d -> tam = d -> tam - 1;
	}
	else
		printf("La palabra no existe");
}

void
dict_pprint (Dict d)
{
	assert(d != NULL);
	hash_pprint(d -> hash);
}

int
dict_length (Dict d)
{
	if(d == NULL)
		return -1;
	return d -> tam;
}

Dict
dict_destroy (Dict d)
{
	if(d == NULL)
		return NULL;
	hash_destroy(d -> hash);
	free(d);
	d = NULL;
	return d;
}

Dict
dict_fromFile(char *nomfile)
{
	Dict d = dict_empty();

	if(d == NULL)
		return NULL;

	d -> hash = hash_destroy(d -> hash);
	d -> hash = hash_fromFile(nomfile);
	d -> tam = hash_length(d -> hash);

	return d;
}

void
dict_toFile(char *nomfile, Dict d)
{
	assert(d != NULL);
	hash_toFile(nomfile , d -> hash);
}

void
perfomance (Dict d)
{
	printf (" Esta es la MEDIA =====> %f\n" ,  media(d->hash));
	printf (" Esta es la VARIANZA =====> %f\n" , varianza(d->hash));
}
